var webView = {};
var origin = window.location.origin;
if (!origin) {
    origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
Object.prototype.exist = function () {
    if (typeof this != 'undefined' && this.length >= 1) {
        return true;
    }
    return false;
};

(function () {
    "use strict";

    var common = {
        _createScript: function (config) {
            var script = document.createElement('script');
            script.type = config.type || 'text/javascript';
            script.async = config.async;
            script.charset = config.charset || 'utf-8';
            script.src = config.url;
            //script.src = config.url + '?v=' + new Date().getTime();
            script.id = config.id || '';
            return script;
        },
        onCreateScript: function (config) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = config.url;
            if (script.attachEvent)
                script.attachEvent("onreadystatechange", config.callback);
            else {
                script.onload = function () {
                    script.onload = function () {};
                    setTimeout(config.callback, 7);
                };
            }
            document.body.appendChild(script);
        },
        onLoadScript: function (config) {
            var body = document.getElementsByTagName('head')[0],
                node = this._createScript({
                    id: config.id + '-js',
                    url: config.url,
                    async: config.async
                });

            // if (node.attachEvent)
            //     node.attachEvent("onreadystatechange", config.callback);
            // else {
            //     node.onload = function () {
            //         node.onload = function () { };
            //         setTimeout(config.callback, 7);
            //     };
            // }
            node.onload = function () {
                node.onload = function () {};
                if (config.callback) setTimeout(config.callback, 7);
            };
            body.appendChild(node);
        },
        onRemoveScript: function (id) {
            var allscript = document.getElementsByTagName('script');
            for (var i = 0; i < allscript.length; i++) {
                if (allscript[i].id == id) {
                    allscript[i].parentNode.removeChild(allscript[i]);
                }
            }
        },

        onLoadStyle: function (id, url, callback) {

            var isload = true;
            var link = document.createElement('link');
            var head = document.getElementsByTagName('head')[0];
            var engine = window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/) || 0;

            if (engine[2] || engine[8] || 'WebkitAppearance' in document.documentElement.style)
                isload = false;

            link.type = 'text/css';
            link.rel = 'stylesheet';
            link.id = id + '-css';

            if (isload)
                link.onload = function () {
                    link.onload = function () {};
                    setTimeout(callback, 7);
                }
            else
                var loadInterval = setInterval(function () {
                    for (var i = 0; i < document.styleSheets.length; i++) {
                        var sheet = document.styleSheets[i];
                        if (sheet.href == link.href) {
                            clearInterval(loadInterval);
                            return callback();
                        }
                    }
                }, 10);
            link.href = url + '?v=' + new Date().getTime();
            head.appendChild(link);
        },
        onRemoveStyle: function (id) {
            var allcss = document.getElementsByTagName('link');
            for (var i = 0; i < allcss.length; i++) {
                if (allcss[i].id == id) {
                    allcss[i].parentNode.removeChild(allcss[i]);
                }
            }
        },

        onGetUrlParams: function () {
            var url = location.search;
            var obj;
            if (url.indexOf("?") != -1) {
                obj = new Object();
                var str = url.substr(1);
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    var val = decodeURI(strs[i].split("=")[1]);
                    if (strs[i].split("=")[0]) {
                        obj[strs[i].split("=")[0]] = val;
                    }
                }
            }
            return obj;
        }
    };

    var dateTime = {
        //时间戳转为日期
        getFormatTimesTamp: function (val) {

            if (val > 2554431132000 || val == 0 || val == undefined) return '-';

            var date = new Date(val);
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }

            var hours = date.getHours();
            if (hours >= 0 && hours <= 9) {
                hours = "0" + hours;
            }

            var min = date.getMinutes();
            if (min >= 0 && min <= 9) {
                min = "0" + min;
            }

            var seconds = date.getSeconds();
            if (seconds >= 0 && seconds <= 9) {
                seconds = "0" + seconds;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
                " " + hours + seperator2 + min + seperator2 + seconds;
            return currentdate;
        },
        //时间戳转为日期 不需要时间字段
        getFormatDateTamp: function (val, seperator) {
            if (val > 2554431132000 || val == 0 || val == null) return '-';

            var date = new Date(val);
            seperator = seperator || "-";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }

            var currentdate = date.getFullYear() + seperator + month + seperator + strDate

            return currentdate;
        },
        //时间戳转为日期 不需要年月日字段
        getFormatTamp: function (val) {
            if (val > 2554431132000 || val == 0) return '-';

            var date = new Date(val);

            var seperator2 = ":";


            var hours = date.getHours();

            if (hours >= 0 && hours <= 9) {
                hours = "0" + hours;
            }

            var min = date.getMinutes();
            if (min >= 0 && min <= 9) {
                min = "0" + min;
            }

            var currentdate = hours + seperator2 + min;
            return currentdate;
        },
        //时间戳转为日期，不要秒字段
        getFormatTimesNotSecond: function (val) {

            if (val > 2554431132000 || val == 0 || val == undefined) return '-';

            var date = new Date(val);
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }

            var hours = date.getHours();
            if (hours >= 0 && hours <= 9) {
                hours = "0" + hours;
            }

            var min = date.getMinutes();
            if (min >= 0 && min <= 9) {
                min = "0" + min;
            }

            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
                " " + hours + seperator2 + min;
            return currentdate;
        },
        //日期转为时间戳
        getDateTimesTamp: function (date) {
            if (!date) return 0;
            date = date.substring(0, 19);
            date = date.replace(/-/g, '/');
            return new Date(date).getTime();
        },
        //获取当天日期
        onGetCurrentDate: function () {
            var date = new Date(),
                year = date.getFullYear(),
                month = date.getMonth() + 1,
                day = date.getDate();
            month = month < 10 ? ('0' + month) : month;
            day = day < 10 ? ('0' + day) : day;
            return year + '-' + month + '-' + day;
        }
    };

    var observe = function (data, callback) {
        if (!data || typeof data !== 'object') {
            return;
        }
        Object.keys(data).forEach(function (key) {
            defineReactive(data, key, data[key], callback);
        });
    };

    var defineReactive = function (data, key, val, callback) {
        observe(val);
        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: true,
            get: function (value) {
                return val;
            },
            set: function (nval) {
                if (val === nval) {
                    return;
                }
                if (typeof nval === 'object' && nval.hasOwnProperty('data')) {
                    val = nval.value;
                } else {
                    val = nval
                }
                callback(nval);
            }
        });
    };

    /**
     * 将GPS国籍坐标转换成高德坐标
     * GPS.gcj_encrypt("纬度","经度");
     * 
     */
    var GPS = {
        PI: 3.14159265358979324,
        x_pi: 3.14159265358979324 * 3000.0 / 180.0,
        delta: function (lat, lon) {
            // Krasovsky 1940
            //
            // a = 6378245.0, 1/f = 298.3
            // b = a * (1 - f)
            // ee = (a^2 - b^2) / a^2;
            var a = 6378245.0;
            //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
            var ee = 0.00669342162296594323;
            //  ee: 椭球的偏心率。
            var dLat = this.transformLat(lon - 105.0, lat - 35.0);
            var dLon = this.transformLon(lon - 105.0, lat - 35.0);
            var radLat = lat / 180.0 * this.PI;
            var magic = Math.sin(radLat);
            magic = 1 - ee * magic * magic;
            var sqrtMagic = Math.sqrt(magic);
            dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
            dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
            return {
                'lat': dLat,
                'lon': dLon
            };
        },
        //GPS---高德
        gcj_encrypt: function (wgsLat, wgsLon) {
            if (this.outOfChina(wgsLat, wgsLon))
                return {
                    'lat': wgsLat,
                    'lon': wgsLon
                };

            var d = this.delta(wgsLat, wgsLon);
            return {
                'lat': wgsLat + d.lat,
                'lon': wgsLon + d.lon
            };
        },
        outOfChina: function (lat, lon) {
            if (lon < 72.004 || lon > 137.8347)
                return true;
            if (lat < 0.8293 || lat > 55.8271)
                return true;
            return false;
        },
        transformLat: function (x, y) {
            var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
            ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
            return ret;
        },
        transformLon: function (x, y) {
            var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
            ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
            return ret;
        }
    };

    ///格式化数字
    function formatNumber(n) {
        n = n.toString()
        return n[1] ? n : '0' + n
    };

    // 处理站点格式 站点id_线路id
    function changeFormat(that) {
        var value = "";
        var myArr = that.data;
        for (var i = 0; i < myArr.length; i++) {
            if (i == myArr.length - 1) {
                value += myArr[i].id + "_" + myArr[i].line_id;
            } else {
                value += myArr[i].id + "_" + myArr[i].line_id + ",";
            }
        };
        return value
    };

    /** 
     * 根据经纬度计算距离 丰泽客运站24.880821, 118.609329
     * res[0] 距离 米
     * res[1] 时间 分钟
     */
    function getDistance(lon1, lat1, lon2, lat2) {
        var d1 = 0.01745329251994329;
        var d2 = lon1;
        var d3 = lat1;
        var d4 = lon2;
        var d5 = lat2;
        d2 *= d1;
        d3 *= d1;
        d4 *= d1;
        d5 *= d1;
        var d6 = Math.sin(d2);
        var d7 = Math.sin(d3);
        var d8 = Math.cos(d2);
        var d9 = Math.cos(d3);
        var d10 = Math.sin(d4);
        var d11 = Math.sin(d5);
        var d12 = Math.cos(d4);
        var d12 = Math.cos(d4);
        var d13 = Math.cos(d5);
        var arrayOfDouble1 = [];
        var arrayOfDouble2 = [];
        arrayOfDouble1.push(d9 * d8);
        arrayOfDouble1.push(d9 * d6);
        arrayOfDouble1.push(d7);
        arrayOfDouble2.push(d13 * d12);
        arrayOfDouble2.push(d13 * d10);
        arrayOfDouble2.push(d11);
        var d14 = Math.sqrt((arrayOfDouble1[0] - arrayOfDouble2[0]) * (arrayOfDouble1[0] - arrayOfDouble2[0]) + (arrayOfDouble1[1] - arrayOfDouble2[1]) * (arrayOfDouble1[1] - arrayOfDouble2[1]) + (arrayOfDouble1[2] - arrayOfDouble2[2]) * (arrayOfDouble1[2] - arrayOfDouble2[2]));

        var s = (Math.asin(d14 / 2.0) * 12742001.579854401);
        return s;
    };

    /**
     * lat :当前经度 str
     * lon：当前纬度 str
     * arr: 所有站点经纬度 array
     * 返回离当前定位最近站点id str
     */
    function getMinDis(lat, lon, arr) {
        var newArr = [];
        for (var i = 0; i < arr.length; i++) {
            newArr[i] = getDistance(lat, lon, arr[i].lat, arr[i].lon);
        }
        var j = arrayMin(newArr);
        var res = arr[j].id;
        return res;
    };

    // 查找数组中最小值 return key
    function arrayMin(arrs) {
        var min = arrs[0];
        var j = 0;
        for (var i = 1, ilen = arrs.length; i < ilen; i += 1) {
            if (arrs[i] < min) {
                min = arrs[i];
                j = i;
            }
        }
        return j;
    };

    var request = {
        queryParams: function (data, isPrefix) {
            isPrefix = isPrefix ? isPrefix : false
            var prefix = isPrefix ? '?' : ''
            var _result = []
            for (var key in data) {
                var value = data[key]
                // 去掉为空的参数
                if (['', undefined, null].includes(value)) {
                    continue
                }
                if (value.constructor === Function) {
                    continue;
                }
                if (value.constructor === Array) {
                    for (var _value in value) {
                        _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(value[_value]))
                    }
                } else {
                    _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
                }
            }
            return _result.length ? prefix + _result.join('&') : ''
        },
        onGetLogin: function () {
            return {};
        },
        onSendRequest: function (config) {

            if (config.method == 'get') {
                var obj = JSON.parse(config.param);
                delete obj.__proto__;
                var str = this.queryParams(obj, '');
                config.url += '?v=1&' + str;
            }

            $.ajax({
                url: config.url,
                cache: false,
                async: config.async,
                type: config.method ? config.method : 'get',
                contentType: config.contentType,
                data: config.param,
                dataType: config.dataType,
                //crossDomain: true == !(document.all),  //兼容ie9跨域访问接口
                timeout: config.timeout,
                success: function (jd) {
                    config.success(jd);
                },
                error: config.error,
                //headers: headers,
                complete: function (XMLHttpRequest, textStatus) {}
            });
        },
        onCreateRequest: function (url, param) {
            this.url = url;
            this.param = param;
            this.method = 'post';
            this.timeout = 20000;
            this.async = true;
            this.cache = false;
            this.contentType = 'application/json';
            this.dataType = 'json';
            this.complete = null;
            this.success = null;
            this.error = function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                return;
            };
        },
        onAjaxRequest: function (config) {

            var json = JSON.stringify(config.param);
            var packet = new this.onCreateRequest(config.url, json);

            if (config.method) packet.method = config.method;
            if (typeof config.async != 'undefined') packet.async = config.async;

            packet.success = function (jd) {

                config.success(jd);
            };
            packet.error = function (error) {

                console.log('网络异常');
            };
            if (config.error) packet.error = config.error;
            if (config.dataType) packet.dataType = config.dataType;
            this.onSendRequest(packet);
        },
    };

    //缓存
    var cache = {
        set: function (key, value) {
            localStorage.setItem(key, value);
        },
        get: function (key) {
            return localStorage.getItem(key);
        },
        remove: function (key) {
            localStorage.removeItem(key);
        }
    };

    webView = {
        cache: cache,
        common: common,
        observe: observe,
        dateTime: dateTime,
        request: request,
        defineReactive: defineReactive
    };

    window.webView = webView;
})();

(function () {
    "use strict";

    var markView = {
        node: null,
        vlid: function () {
            if (this.node) {
                if (this.node.className.indexOf('ui-mark-show') > -1)
                    return true;
            }
            return false;
        },
        show: function (type, msg) {
            if (this.node) {
                node.className.replace('ui-mark-hide', 'ui-mark-show');
                return;
            }
            this.create(type, msg);
        },
        hide: function () {
            if (!this.node) {
                return;
            }
            this.node.className.replace('ui-mark-show', 'ui-mark-hide');
        },
        create: function (type, msg) {
            var container = document.createElement('div');
            container.id = 'ui-mark-overlay';
            container.className = 'ui-ios-overlay ui-overlay-show ui-mark-show';

            var title = document.createElement('span');
            title.className = 'title';
            title.textContent = msg || '正在加载中...';

            var img = document.createElement('img');
            if (type == 1)
                img.src = '../img/common/check.png';
            else if (type == 2) {
                img.src = '../img/common/cross.png';
            } else {
                img.src = '../img/common/load.gif';
            }

            container.appendChild(title);
            container.appendChild(img);

            markView.node = container;
            document.body.appendChild(container);
        }
    };
    window.widget = {
        markView: markView
    };


})();